import Vue from "vue";
import Message from "./index.vue";
let MsgConstructor = Vue.extend(Message); // 生成vc的构造函数
let instant;
let instants = [];
let seed = 0;
const Msg = (options) => {
	if (typeof options === "string") {
		options = {
			msg: options,
		};
	}
	let userOnClose = options.onClose; //用户传的关闭时的回调函数
	let id = "my_message_" + seed++; // 给每个vc 绑定唯一id
	options.onClose = function () {
		//触发定时器结束关闭消息的回调，在这里可移除数组intstants中关闭的消息
		Msg.close(id, userOnClose);
	};
	instant = new MsgConstructor({
		// 构造一个vc实例对象(生成一条消息)
		data: options,
	});
	instant.id = id;
	instant.$mount(); //将实例挂到index.html中的body下
	document.body.appendChild(instant.$el);
	instant.isShow = true; //将isShow 属性设置为true（用于过渡动画切换）
	let topOffset = options.offset || 20;
	if (instants.length === 0) {
		instant.topOffset = 20;
	}
	instants.forEach((item) => (topOffset += item.$el.offsetHeight + 16)); // 设置style的top值
	instant.topOffset = topOffset;
	instant.$el.style.zIndex = seed * 10000;
	instants.push(instant);
	return instant;
};
//  四种不同类型的消息
let types = ["info", "success", "warning", "error"];
types.forEach((type) => {
	Msg[type] = (options) => {
		if (typeof options === "object") {
			return Msg({
				type,
				...options,
			});
		}
		return Msg({
			type,
			msg: options,
		});
	};
});
Msg.close = (id, userOnClose) => {
	let removeHeight;
	try {
		instants.forEach((item, index) => {
			if (id === item.id) {
				// 如果用户设置了回调，就在关闭时执行回调
				if (typeof userOnClose === "function") {
					userOnClose(item);
				}
				removeHeight = item.$el.offsetHeight;
				instants.splice(index, 1); // 移除当前的实例
				throw new Error("终止"); //终止当前循环
			}
		});
	} catch (e) {
		//TODO handle the exception
  }
	// 如果只有小于等于一条数据则直接返回
	if (instants.length <= 0) return;
  instants.forEach((item, index) => {
    console.log(index)
		item.$el.style.top = parseInt(item.$el.style.top) - removeHeight - 16 + "px"; //给以后的实例设置top
	});
};
export default Msg;
